import pagedTable from './common/pagedTable'
import {
  getUserNotifications,
  setNotificationAsRead,
  setAllNotificationsAsRead,
  deleteNotification,
  getNotificationSettings,
  updateNotificationSettings
} from '@/api/notification'

const notification = {
  namespaced: true,
  state: {
    ...pagedTable.state,

    top3Notifications: {}
  },
  mutations: {
    ...pagedTable.mutations
  },
  actions: {
    ...pagedTable.actions,

    getAll({ state }, payload) {
      return new Promise((resolve, reject) => {
        state.loading = true
        getUserNotifications(payload.data)
          .then(response => {
            state.list = []
            state.list.push(...response.data.result.items)
            state.totalCount = response.data.result.totalCount
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
          .finally(() => {
            state.loading = false
          })
      })
    },

    getTop3({ state }) {
      return new Promise((resolve, reject) => {
        getUserNotifications({ maxResultCount: 3, skipCount: 0 })
          .then(response => {
            state.top3Notifications = response.data.result
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    setNotificationAsRead({ dispatch }, id) {
      return new Promise((resolve, reject) => {
        setNotificationAsRead({ id })
          .then(response => {
            dispatch('getTop3')
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    setAllNotificationsAsRead({ dispatch }) {
      return new Promise((resolve, reject) => {
        setAllNotificationsAsRead()
          .then(response => {
            dispatch('getTop3')
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    deleteNotification({ dispatch }, Id) {
      return new Promise((resolve, reject) => {
        deleteNotification(Id)
          .then(response => {
            dispatch('getTop3')
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    getNotificationSettings() {
      return new Promise((resolve, reject) => {
        getNotificationSettings()
          .then(response => {
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    updateNotificationSettings({ state }, payload) {
      return new Promise((resolve, reject) => {
        updateNotificationSettings(payload)
          .then(response => {
            resolve(response.data.result)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}

export default notification
